﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace IoTCM
{
    public class JsonSerializer : IObjectSerializer
    {
        private Newtonsoft.Json.JsonSerializer m_serializer;
        private DataValueCollectionConverter m_converter;

        public JsonSerializer()
        {
            m_serializer = new Newtonsoft.Json.JsonSerializer();
            m_converter = new DataValueCollectionConverter();
        }

        public string Serialize(Thing things)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(things, Newtonsoft.Json.Formatting.Indented);
        }

        public string Serialize(DataValueCollection values)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(values, Newtonsoft.Json.Formatting.Indented, m_converter);
        }

        public IEnumerable<DataValue> DeserializeValues(string serializedValues)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<DataValue>>(serializedValues);
        }

    }

    internal class DataValueCollectionConverter : Newtonsoft.Json.JsonConverter
    {
        private class ConversionSurrogate
        {
            public ConversionSurrogate(DataValueCollection values)
            {
                Instance = values.Instance;
                Timestamp = values.Timestamp;
                Values = values.ToList();
            }

            public string Instance { get; set; }
            public DateTime Timestamp { get; set; }

            public List<DataValue> Values { get; set; }

        }

        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            var surrogate = new ConversionSurrogate((DataValueCollection)value);
            serializer.Serialize(writer, surrogate);
        }

        public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DataValueCollection);
        }
    }

}
